package cn.tedu.shopol.taojin.service.impl;

import cn.tedu.shopol.taojin.dto.RegisterClientDTO;
import cn.tedu.shopol.taojin.ex.InsertException;
import cn.tedu.shopol.taojin.ex.PhoneDuplicateException;
import cn.tedu.shopol.taojin.model.User;
import cn.tedu.shopol.taojin.mapper.UserMapper;
import cn.tedu.shopol.taojin.service.IUserService;
import cn.tedu.shopol.taojin.util.PasswordUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2020-12-08
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    UserMapper userMapper;


    @Override
    public void registerClient(RegisterClientDTO registerClientDTO) {
        // 基于参数phone调用userMapper.findByPhone()执行查询
        User result = userMapper.findByPhone(registerClientDTO.getPhone());
        // 判断查询结果是否不为null
        if (result != null) {
            //是,抛出异常
            throw new PhoneDuplicateException("注册失败!手机号已被注册!");
        }
        // 创建当前时间对象now
        LocalDateTime now = LocalDateTime.now();
        // 创建User对象
        User user = new User();
        // 补全user对象的属性值：userName < 参数userName
        user.setUsername(registerClientDTO.getUsername());
        // 补全user对象的属性值：nickName < 参数nickName
        user.setNickname(registerClientDTO.getNickname());
        // 补全user对象的属性值：password < 参数password
        String rawPassword = registerClientDTO.getPassword();
        String encodePassword = PasswordUtils.encode(rawPassword);
        user.setPassword(encodePassword);
        // 补全user对象的属性值：phone < 参数phone
        user.setPhone(registerClientDTO.getPhone());
        // 补全user对象的属性值：email < 参数email
        user.setEmail(registerClientDTO.getEmail());
        // 补全user对象的属性值：Create_Time < now
        user.setCreateTime(now);
        // 补全user对象的属性值：Update_Time < now
        user.setUpdateTime(now);
        // 基于以上user对象调用userMapper.insert()执行插入数据，并获取返回的“受影响行数”
        int rows = userMapper.insert(user);
        // 判断以上返回的“受影响行数”是否不为1
        if (rows != 1) {
            // 是：抛出InsertException
            throw new InsertException("注册失败!服务器繁忙,请稍后重试...");
        }
    }
}
